package com.andy.web.util;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MailUtil {
	
	private static Logger LOGGER = LoggerFactory.getLogger(MailUtil.class);
	
	private static String from = "wbcommon@163.com"; // 发件人邮箱地址
	private static String user = "wbcommon@163.com"; // 发件人称号，同邮箱地址
	private static String password = "weibiao001"; // 发件人邮箱客户端授权码

	/**
	 * 发送文本
	 * @param to 
	 * @param text
	 * @param title
	 * @return2018年5月13日Administrator下午9:52:09
	 */
	public static boolean sendMailWithText(String targetMail, String title, String text) {
		
		//1.0 prepare
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", "smtp.163.com"); // 设置发送邮件的邮件服务器的属性（这里使用网易的smtp服务器）
		props.put("mail.smtp.host", "smtp.163.com"); // 需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）
		props.put("mail.smtp.auth", "true"); 
		Session session = Session.getDefaultInstance(props); // 有了这句便可以在发送邮件的过程中在console处显示过程信息，供调试使
		session.setDebug(true); // 用session为参数定义消息对象
		MimeMessage message = new MimeMessage(session); 

		try {
			//2. set email content
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(targetMail)); 
			message.setSubject(title); 

			Multipart multipart = new MimeMultipart(); // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
			BodyPart contentPart = new MimeBodyPart(); // 设置邮件的文本内容
			contentPart.setContent(text, "text/html;charset=utf-8");
			multipart.addBodyPart(contentPart);
			message.setContent(multipart);
			message.saveChanges(); // 保存变化
			
			//3. send and close
			Transport transport = session.getTransport("smtp"); // 连接服务器的邮箱
			transport.connect("smtp.163.com", user, password); 
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			LOGGER.error(String.format("Email send failed, target email:[%s], title:[%s], "
					+ "text:[%s], error stack:[%s]", targetMail,title, text, e.getMessage()));
			return false;
		}
		return true;
	}

	public static void main(String[] args) { // 做测试用
		MailUtil ds = new MailUtil();
		ds.sendMailWithText("2194491997@qq.com", "你好，这是一封测试邮件，无需回复。", "测试邮件");
	}
}